################################
#	John Henderson
#	Gerrymandering Incumbency 
#		(with Brian Hamel and Aaron Goldzimer)
#		April 9, 2017    
#
################################
# code edits that produced by Chen & Rodden (2013), to replicate their 2000 analysis 
#  for competitiveness outcomes                                                 
################################
# calls sims2000.R to load data for plotting

rm(list=ls())    

GetColorHexAndDecimal <- function(color)
{
  c <- col2rgb(color)
  sprintf("#%02X%02X%02X %3d %3d %3d", c[1],c[2],c[3], c[1], c[2], c[3])
}

library(stringr)  
library(foreign)

setwd("~/Dropbox/StateRedistricting/replication/short/")
source('sims2010.R')

#########################
# cd flip prob
#########################


{
pdf(width=5,height=9,file='cd_2010-flip.pdf')
plot(x=-1000, y=-1000, type='n', xlim=c(-.18, 1), ylim=c(.5,43), axes=F, ylab="", xlab="")#, main=paste("Margins of Victory in House Elections\n",state,sep=""))
axis(1,at=c(0,.25,.5,.75,1),labels=c(0,.25,.5,.75,1))
#cnts=0
cnts=44        



legend(cex=.7,y=cnts-12.25,x=.428,border=F,box.lty=1,legend=c('Enacted Plan','Simulated Plan'),	
 col=c('red',gray(.65)),lwd=c(1,1),pch=c(1,19),lty=c(NA,NA))


#Means and Medians
for (state in states_ix){
	cnts=cnts-1
	    		
	fls=paste('sims2010/',state,'/plans/',length(which(e08[,1]==state)),'.txt',sep='')   
	if(file.exists(fls)){
		cds=read.table(fls)[,-c(1)]  		
		cd08=e08$mcnshare[which(e08[,1]==state)]		      
	} else if(!file.exists(fls)){
		fla=fls                        
		pp=0
		while(!file.exists(fla) & pp<60){
			pp=pp+1
			fla=paste('sims2010/',state,'/plans/',pp,'.txt',sep='')   					
		}
		fls=fla 
		if(file.exists(fls)){ 
			cds=read.table(fls)[,-c(1)]  
			cd08=e08$mcnshare[which(e08[,1]==state)]			   
		} else{
			#next(paste(states[j],'has no simulations',sep=' '))  
			cds=rbind(0,0)
			cd08=0
		}
	}          
	
	temp.sims = cds 	
	temp.10 = cd08

	#order margins
	for(i in 1:nrow(temp.sims)){
		temp.sims[i,]=sort(temp.sims[i,])
	}
    temp.10=sort(temp.10) 	

	means.sim=apply((temp.sims-(1-temp.sims)),1,flipPr,state,year_mins,year_maxs)     
	mean.10=flipPr((temp.10-(1-temp.10)),state,year_mins,year_maxs)
	ss.dif=mean(mean.10-means.sim)+.001

	#hypothesis-test-like statistics
	#mu=mean(means.sim,na.rm=T)
	#sds=sd(means.sim,na.rm=T) 
	#s.means.sim=((means.sim-mu)/sds)
	#s.mean.02=((mean.02-mu)/sds)	
	#s.dif=mean(s.mean.02-s.means.sim)
	if(ss.dif>0){
		p.dif=sum(mean.10<means.sim)/length(means.sim)    
	} else{                                                     
		p.dif=sum(mean.10>means.sim)/length(means.sim)    
	} 
	     
	cols='red' 
	ltys=2
	if(p.dif<.05){
		cols='red' 
		ltys=1
	}  
	 
	if(length(mean.10)>0){ 	  
		points(x=means.sim, y=jitter(factor=.2,rep(cnts,length(means.sim))), col=gray(.65), lwd=2,pch=20,cex=.52)
		points(y=cnts, x=mean.10, col=cols, pch=1,cex=abs(ss.dif)*8+.58,lty=2) 			
		text(col='black',adj=c(0,NA),x=.015,y=cnts,labels=paste('(',str_sub(ss.dif,1,str_locate(ss.dif,pattern='[/.]')[1]+2),')',sep=''),srt = 1, pos = 2,cex=.5)				
    } else{
		text(col='black',adj=c(0,NA),x=.015,y=cnts,labels='NA',srt = 1, pos = 2,cex=.5)				
	} 
	text(adj=c(0,NA),x=-.11,y=cnts,labels=as.character(state),srt = 1, pos = 2,cex=.65)	

}         
                            
# lines and legend graphics   
lines(col='grey',lty=2,y=c(.5,.5),x=c(-.115,1.))
lines(col='grey',lty=2,y=c(4.5,4.5),x=c(-.115,1.))  
lines(col='grey',lty=2,y=c(13.5,13.5),x=c(-.115,1.))
lines(col='grey',lty=2,y=c(21.5,21.5),x=c(-.115,1.))
lines(col='grey',lty=2,y=c(37.5,37.5),x=c(-.115,1.))
lines(col='grey',lty=2,y=c(43.5,43.5),x=c(-.115,1.))                              
                                          
axis(2,line=-1.5,at=c(.5,4.5,13.5,21.5,37.5,43.5),labels=F,tck=-.02)

text(x=1.-.0105,y=42.,labels='Democratic',cex=.75,adj=c(1,1),srt=0)
text(x=1.-.0105,y=36.,labels='Republican',cex=.75,adj=c(1,1),srt=0)
text(x=1.-.0105,y=20.,labels='Bipartisan',cex=.75,adj=c(1,1),srt=0)
text(x=1.-.0105,y=12.,labels='Court',cex=.75,adj=c(1,1),srt=0) 
text(x=1.-.0105,y=3.,labels='Independent',cex=.75,adj=c(1,1),srt=0) 
mtext("Proportion of Swing Year Flips",side=1,at=.5,adj=.5,line=3) 
dev.off()
}   

#end  